package com.zjitc.controller;

import com.zjitc.pojo.Book;
import com.zjitc.pojo.User;
import com.zjitc.service.BookService;
import com.zjitc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @Autowired
    private UserService userService;

    @RequestMapping("/delete")
    public String delete(int id) {
        bookService.delete(id);
        return "redirect:/users/index";
    }

    @RequestMapping("/updateEntry")
    public ModelAndView updateEntry(int id) {
        Book book = bookService.findOne(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("book", book);
        mv.setViewName("updateBooks");
        return mv;
    }

    @RequestMapping("/update")
    public String update(Book book) {
        bookService.update(book);
        return "redirect:/users/index";
    }

    @RequestMapping("/insertEntry")
    public String insertEntry() {
        return "insertBooks";
    }

    @RequestMapping("/save")
    public ModelAndView save(Book book) {
        book.setLastAt(new Date());
        book.setStatus(0);
        book.setTotal(1);
        bookService.insert(book);
        ModelAndView mv = new ModelAndView();
        List<Book> all = bookService.findAll();
        List<User> users = userService.getUsers(LoginController.role);
        mv.addObject("bookList", all);
        mv.addObject("userList", users);
        mv.setViewName("redirect:/users/index");
        return mv;
    }

    @RequestMapping("/borrow")
    public String borrow(int id) {
        bookService.borrow(id);
        return "redirect:/users/index";
    }

    @RequestMapping("/back")
    public String back(int id) {
        bookService.back(id);
        return "redirect:/users/index";
    }
}
